package com.sunny.hp.common.rss;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.xml.sax.InputSource;

import com.sunny.hp.common.util.DateHelper;



/**
 * 클래스설명 : 
 * @version : 2013. 3. 13.
 * @author : 신용천
 * @분류 : 
 * IBS_SC / package com.hanwha.common.util;
 */

public class WeatherUtil {
	private SAXBuilder parser = null;
	private List<Element> list = null;
	private String regionId = "";

	/**
	 * @param regionCode
	 *
	"01" // 서울/경기(경기 안양 기준)
	"02" // 충북(충북 충주 기준)
	"03" // 충남(충남 아산 기준)
	"04" // 경북(경북 포항 기준)
	"05" // 경남(경남 사천 기준)
	"06" // 전북(전북 남원 기준)
	"07" // 전남(전남 광양 기준)
	"08" // 강원(강원 춘천 기준)
	"09" // 제주(제주 제주 기준)
	"10" // 울릉(경북 울릉 기준)
	 */
	public WeatherUtil(long regionCode, String isRSS){
		try {
			//LinkedHashMap<String, String> regionMap = getWeatherRegion(regionCode);
			parser = new SAXBuilder();  
			parser.setValidation(false);  
			parser.setIgnoringElementContentWhitespace(true);  
			URL url = new URL("http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone="+regionCode); 
			//System.out.println(url);
			InputSource is = new InputSource(url.openStream());  
			Document doc = parser.build(is);  
			//System.out.println("doc ==>" + doc.toString());
			Element root = doc.getRootElement();  
			Element channel = root.getChild("channel");  
			Element item = channel.getChild("item"); 
			Element description = item.getChild("description"); 
			Element body = description.getChild("body"); 
			list = body.getChildren("data");
			//System.out.println("list size ==> " + list.size());
			////System.out.println(getThreeDayWeather());
			getCurrentWeather();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}

	public WeatherUtil(int regionCode){
		try {
			LinkedHashMap<String, String> regionMap = getWeatherRegion(regionCode);
			parser = new SAXBuilder();  
			parser.setValidation(false);  
			parser.setIgnoringElementContentWhitespace(true);  
			URL url = new URL("http://www.kma.go.kr/wid/queryDFS.jsp?gridx="+regionMap.get("gridx")+"&gridy="+regionMap.get("gridy")); 
			//System.out.println(url);
			InputSource is = new InputSource(url.openStream());  
			Document doc = parser.build(is);  
			//System.out.println("doc ==>" + doc.toString());
			Element root = doc.getRootElement();   
			Element channel = root.getChild("body");  
			list = channel.getChildren("data");

			////System.out.println(getThreeDayWeather());
			getCurrentWeather();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}
	public WeatherUtil(int gridx, int gridy){
		try {
			//			LinkedHashMap<String, String> regionMap = getWeatherRegion(regionCode);
			parser = new SAXBuilder();  
			parser.setValidation(false);  
			parser.setIgnoringElementContentWhitespace(true);  
			URL url = new URL("http://www.kma.go.kr/wid/queryDFS.jsp?gridx="+gridx+"&gridy="+gridy); 
			//System.out.println(url);
			InputSource is = new InputSource(url.openStream());  
			Document doc = parser.build(is);  
			Element root = doc.getRootElement();   
			Element channel = root.getChild("body");  
			list = channel.getChildren("data");

			////System.out.println(getThreeDayWeather());
			getCurrentWeather();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}


	/** 날짜별 날씨 데이터를 가져온다.
	 * @return
	 * 시간 : + el.getChildText("hour")); // 시간(3시간 단위)
		오늘 : + el.getChildText("day"));  // 오늘 (++)
		기온 : + el.getChildText("temp")); // 기온
		최대온도 : + el.getChildText("tmx"));  // 최대온도
		최저온도 : + el.getChildText("tmn"));  // 최저온도
		날씨 코드 : + el.getChildText("sky"));  // 날씨 코드
		날씨(한글) : + el.getChildText("wfKor"));  // 날씨(한글)
		날씨(영문) : + el.getChildText("wfEn"));  // 날씨(영문)
		강수확률 : + el.getChildText("pop"));  // 강수확률
		습도 : + el.getChildText("reh"));  // 습도
	 */
	public LinkedHashMap<String, String> getCurrentWeather(){
		DateHelper dateHelper = new DateHelper();
		dateHelper.initialize();

		LinkedHashMap<String, String> weatherMap = new LinkedHashMap<String, String>();

		if(list != null){
			for(Element el : list){
				String seq = el.getAttributeValue("seq");
				if ("0".equals(seq)) {
					for (Element el2 : (List<Element>)el.getChildren()) {
						String weatherCode = "";
						weatherMap.put(el2.getName(), el.getChildText(el2.getName()));
						String wfKorText = el.getChildText("wfKor");
						if(wfKorText.equals("맑음")){
							weatherCode = "01";
						}else if(wfKorText.equals("구름 조금")){
							weatherCode = "02";
						}else if(wfKorText.equals("구름 많음")){
							weatherCode = "03";
						}else if(wfKorText.equals("흐림")){
							weatherCode = "04";
						}else if(wfKorText.equals("비")){
							weatherCode = "05";
						}else if(wfKorText.equals("눈/비")){
							weatherCode = "06";
						}else if(wfKorText.equals("눈")){
							weatherCode = "07";
						}
						weatherMap.put("wcd", weatherCode);

					}
				}
			}

			if(weatherMap.size() == 0){
				Element el = list.get(0);
				List<Element> a = el.getChildren();
				for(Element el2 : a){
					weatherMap.put(el2.getName(), el.getChildText(el2.getName()));
				}

			}
		}

		//System.out.println(weatherMap);
		return weatherMap;
	}

	/** 날짜별 날씨 데이터를 가져온다.
	 * @return
	 * 시간 : + el.getChildText("hour")); // 시간(3시간 단위)
		오늘 : + el.getChildText("day"));  // 오늘 (++)
		기온 : + el.getChildText("temp")); // 기온
		최대온도 : + el.getChildText("tmx"));  // 최대온도
		최저온도 : + el.getChildText("tmn"));  // 최저온도
		날씨 코드 : + el.getChildText("sky"));  // 날씨 코드
		날씨(한글) : + el.getChildText("wfKor"));  // 날씨(한글)
		날씨(영문) : + el.getChildText("wfEn"));  // 날씨(영문)
		강수확률 : + el.getChildText("pop"));  // 강수확률
		습도 : + el.getChildText("reh"));  // 습도
	 */
	public JSONArray getThreeDayWeather(){
		JSONArray weatherTag = new JSONArray();

		JSONArray [] weatherArray = {new JSONArray(),new JSONArray(), new JSONArray()};
		JSONObject [] weatherObject = {new JSONObject(),new JSONObject(), new JSONObject()};
		JSONObject [] weatherNameObject = {new JSONObject(),new JSONObject(), new JSONObject()};
		DateHelper dh = new DateHelper();

		for(Element el : list){

			List<Element> a = el.getChildren();
			String day = el.getChildText("day");
			JSONObject obj = weatherObject[Integer.parseInt(day)];
			JSONArray objArray = weatherArray[Integer.parseInt(day)];
			JSONObject obj_ = new JSONObject();
			for(Element el2 : a){
				////System.out.println(el2.getName() + " : " + el.getChildText(el2.getName()));


				String weatherCode = "";
				obj_.put(el2.getName(), el.getChildText(el2.getName()));
				String wfKorText = el.getChildText("wfKor");
				if(wfKorText.equals("맑음")){
					weatherCode = "01";
				}else if(wfKorText.equals("구름 조금")){
					weatherCode = "02";
				}else if(wfKorText.equals("구름 많음")){
					weatherCode = "03";
				}else if(wfKorText.equals("흐림")){
					weatherCode = "04";
				}else if(wfKorText.equals("비")){
					weatherCode = "05";
				}else if(wfKorText.equals("눈/비")){
					weatherCode = "06";
				}else if(wfKorText.equals("눈")){
					weatherCode = "07";
				}
				obj_.put("wcd", weatherCode);


			}
			//			//System.out.println(day);
			objArray.add(obj_);

		}

		for(int i = 0 ; i < weatherNameObject.length ; i++){
			weatherNameObject[i].put("d" + i, weatherArray[i]);
			weatherTag.add(weatherNameObject[i]);
		}

		//		//System.out.println(weatherTag2);

		return weatherTag;
	}
	/*
	"01" // 서울/경기(경기 안양 기준)
	"02" // 충북(충북 충주 기준)
	"03" // 충남(충남 아산 기준)
	"04" // 경북(경북 포항 기준)
	"05" // 경남(경남 사천 기준)
	"06" // 전북(전북 남원 기준)
	"07" // 전남(전남 광양 기준)
	"08" // 강원(강원 춘천 기준)
	"09" // 제주(제주 제주 기준)
	"10" // 울릉(경북 울릉 기준)
	 */
	public static LinkedHashMap<String, String> getWeatherRegion(int regionCode){
		LinkedHashMap<String, String> regionCdMap = new LinkedHashMap<String, String>();
		String [] gridx = {"59","75","59","105","80","67","74","72","53","127"};
		String [] gridy = {"123","115","110","94","73","80","70","133","38","127"};
		regionCdMap.put("gridx", gridx[regionCode+1]);
		regionCdMap.put("gridy", gridy[regionCode+1]);
		return regionCdMap;

	}

	public static void main(String[] args) throws Exception{

		//new WeatherUtil(01);
		//System.out.println(new WeatherUtil(1).getThreeDayWeather());
		//		LinkedHashMap<String, String> regionMap = getWeatherRegion(1); 
		//		WeatherUtil wu = new WeatherUtil(regionMap.get("gridx"),regionMap.get("gridy"));
		//		 //System.out.println(wu.getThreeDayWeather());
	}
}
